package xxl.robotlegs.extensions.mediatormap.impl 
{
	import flash.utils.Dictionary;
	import xxl.robotlegs.extensions.matching.api.ITypeFilter;
	import xxl.robotlegs.extensions.mediatormap.api.IMediatorConfigurator;
	import xxl.robotlegs.extensions.mediatormap.api.IMediatorMapper;
	import xxl.robotlegs.extensions.mediatormap.api.IMediatorMapping;
	import xxl.robotlegs.extensions.mediatormap.api.IMediatorUnmapper;
	import xxl.robotlegs.framework.api.ILogger;
	/**
	 * ...
	 * @author XXL
	 */
	public class MediatorMapper implements IMediatorMapper, IMediatorUnmapper
	{
		private const _mappings:Dictionary = new Dictionary();
		private var _typeFilter:ITypeFilter;
		private var _handler:MediatorViewHandler;
		private var _logger:ILogger;
		
		public function MediatorMapper(typeFilter:ITypeFilter, handler:MediatorViewHandler, logger:ILogger = null) 
		{
			_typeFilter = typeFilter;
			_handler = handler;
			_logger = logger;
		}
		
		private function createMapping(mediatorClass:Class):MediatorMapping
		{
			const mapping:MediatorMapping = new MediatorMapping(_typeFilter, mediatorClass);
			_handler.addMapping(mapping);
			_mappings[mediatorClass] = mapping;
			_logger && _logger.debug("{0} 映射到 {1}", [_typeFilter, mapping]);
			return mapping;
		}
		
		private function deleteMapping(mapping:IMediatorMapping):void
		{
			_handler.removeMapping(mapping);
			delete _mappings[mapping.mediatorClass];
			_logger && _logger.debug("{0} 从 {1} 取消映射", [_typeFilter, mapping]);
		}
		
		private function overwriteMapping(mapping:IMediatorMapping):MediatorMapping
		{
			_logger && _logger.warn("{0} 重复映射到 {1}了", [_typeFilter, mapping]);
			deleteMapping(mapping);
			return createMapping(mapping.mediatorClass);
		}
		
		/* INTERFACE xxl.robotlegs.extensions.mediatormap.api.IMediatorMapper */
		
		public function toMediator(mediatorClass:Class):IMediatorConfigurator 
		{
			const mapping:IMediatorMapping = _mappings[mediatorClass];
			return mapping
				? overwriteMapping(mapping)
				: createMapping(mediatorClass);
		}
		
		/* INTERFACE xxl.robotlegs.extensions.mediatormap.api.IMediatorUnmapper */
		
		public function fromMediator(mediatorClass:Class):void 
		{
			const mapping:IMediatorMapping = _mappings[mediatorClass];
			mapping && deleteMapping(mapping);
		}
		
		public function fromAll():void 
		{
			for each(var mapping:IMediatorMapping in _mappings)
			{
				deleteMapping(mapping);
			}
		}
		
	}

}